package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.pojo.Setmeal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: bowen
 * @Date: 2019/6/25 17:22
 * @Description:套餐服务类
 */
@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealDao setmealDao;


    @Autowired
    JedisPool jedisPool;

    /**
     * @描述：新增套餐
     */
    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        //    新增基本信息
        setmealDao.add(setmeal);
        Integer id = setmeal.getId();
        //    新增关联信息
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            //    建立套餐id和检查组的关联关系
            setRelationsBetweenSetmealIdAndCheckgroupId(id, checkgroupIds);
        }
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, setmeal.getImg());

    }

    @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage, pageSize);
        Page<Setmeal> setmealPage = setmealDao.findPage(queryString);

        return new PageResult(setmealPage.getTotal(), setmealPage.getResult());
    }

    /**
     * @描述：获取套餐列表
     */
    @Override

    public List<Setmeal> getSetmeal() {
        String fasd = jedisPool.getResource().get("SETMEAL_LIST");
        if (ObjectUtils.isEmpty(fasd)) {
            List<Setmeal> setmeal = setmealDao.getSetmeal();
            String s = JSON.toJSONString(setmeal);
            jedisPool.getResource().set("SETMEAL_LIST", s);
            return setmeal;
        } else {
            return JSON.parseArray(fasd, Setmeal.class);
        }
    }


    /**
     * @描述：根据id查询套餐详情
     */
    @Override
    public Setmeal findById(Integer id) {
        return setmealDao.findById(id);
    }


    private void setRelationsBetweenSetmealIdAndCheckgroupId(Integer setmealId, Integer[] checkgroupIds) {
        for (Integer checkgroupId : checkgroupIds) {
            Map<String, Integer> map = new HashMap<>();
            map.put("setmealId", setmealId);
            map.put("checkgroupId", checkgroupId);
            setmealDao.setRelationsBetweenSetmealIdAndCheckgroupId(map);
        }
    }
}
